<template>
<!--  <n-card :bordered="false">-->
<!--    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">-->
<!--      <template #statusSlot="{ model, field }">-->
<!--        <n-input v-model:value="model[field]" />-->
<!--      </template>-->
<!--    </BasicForm>-->
<!--  </n-card>-->
  <n-card :bordered="false" class="mt-3">
    <BasicTable
      :columns="disasterColumns"
      :request="loadDataTable"
      :row-key="(row:DisasterData) => row.disasterID"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
      :striped="true"
    >
      <template #tableTitle>
        <n-space>
          <n-button type="primary" @click="handleRefresh">
            <template #icon>
              <n-icon>
                <ReloadOutlined />
              </n-icon>
            </template>
            刷新
          </n-button>
        </n-space>
      </template>
    </BasicTable>
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { disasterColumns, DisasterData } from './columns';
import { ReloadOutlined } from '@vicons/antd';
import { useMessage } from 'naive-ui';
import { RoadDisasterApi } from '@/api/RoadDisasterApi';
import { useRouter } from 'vue-router';

const actionRef = ref();
const message = useMessage();
const router = useRouter();

// 表单配置
const schemas: FormSchema[] = [
  {
    field: 'disasterType',
    component: 'NSelect',
    label: '灾害类型',
    componentProps: {
      placeholder: '请选择灾害类型',
      options: [
        { label: '全部', value: '' },
        { label: '洪水', value: '洪水' },
        { label: '火灾', value: '火灾' },
        { label: '地震', value: '地震' },
        { label: '塌方', value: '塌方' },
        { label: '泥石流', value: '泥石流' },
        { label: '道路损坏', value: '道路损坏' },
        { label: '交通事故', value: '交通事故' },
        { label: '其他', value: '其他' },
      ],
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        { label: '全部', value: '' },
        { label: '待验证', value: 'unverified' },
        { label: '已验证', value: 'verified' },
        { label: '已解决', value: 'resolved' },
      ],
    },
  },
];

const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

// 操作列定义
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '查看',
          onClick: handleView.bind(null, record),
        },
        {
          label: '验证',
          onClick: handleVerify.bind(null, record),
          ifShow: () => record.status === 'unverified',
          type: 'success',
        },
        {
          label: '标记解决',
          onClick: handleResolve.bind(null, record),
          ifShow: () => record.status === 'verified',
          type: 'warning',
        },
      ],
    });
  },
});

// 加载表格数据
const loadDataTable = async (res) => {
  try {
    // 获取查询参数
    const params = getFieldsValue();

    // 添加分页参数
    const queryParams = {
      ...params,
      pageNum: res.page,
      pageSize: res.pageSize,
    };

    // 调用API获取灾害列表
    const data = await RoadDisasterApi.getAllRoadDisasters(queryParams);

    // 检查返回的数据格式
    let parsedData = data;


    // 确保parsedData是数组
    if (!Array.isArray(parsedData)) {
      console.warn('返回的数据不是数组:', parsedData);
      parsedData = [];
    }

    console.log('解析后的灾害列表数据:', parsedData);

    return {
      list: parsedData,
      page: res.page,
      pageSize: res.pageSize,
      pageCount: Math.ceil((parsedData?.length || 0) / res.pageSize),
      itemCount: parsedData?.length || 0,
    };
  } catch (error) {
    console.error('获取灾害列表失败:', error);
    message.error('获取灾害列表失败: ' + (error.message || '未知错误'));
    return {
      list: [],
      page: 1,
      pageSize: 10,
      pageCount: 0,
      itemCount: 0,
    };
  }
};

// 选中行事件
function onCheckedRow(rowKeys) {
  console.log('选中的行:', rowKeys);
}

// 刷新表格
function handleRefresh() {
  actionRef.value.reload();
  message.success('刷新成功');
}

// 查看灾害详情
function handleView(record: DisasterData) {
  router.push({
    name: 'disaster_detail',
    params: {
      id: record.disasterID
    }
  });
}

// 验证灾害
async function handleVerify(record: DisasterData) {
  try {
    await RoadDisasterApi.updateDisasterStatus(record.disasterID, 'verified');
    message.success('灾害已验证');
    handleRefresh();
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}

// 标记灾害已解决
async function handleResolve(record: DisasterData) {
  try {
    await RoadDisasterApi.updateDisasterStatus(record.disasterID, 'resolved');
    message.success('灾害已标记为解决');
    handleRefresh();
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}

// 提交表单
function handleSubmit() {
  actionRef.value.reload();
}

// 重置表单
function handleReset() {
  actionRef.value.reload();
}
</script>

<style lang="less" scoped></style>
